import { makeAutoObservable } from 'mobx';
import Web3 from 'web3';

class Web3DemoStore {
    constructor() {
        makeAutoObservable(this, {}, { deep: false });
    }

    web3: Web3 | null = null;
    account = '';
    balance = '0';
    networkId = '';
    isConnected = false;
    contractResult = '';
    activeTab = 'wallet';

    setWeb3(web3: Web3 | null) {
        this.web3 = web3;
    }

    setAccount(account: string) {
        this.account = account;
    }

    setBalance(balance: string) {
        this.balance = balance;
    }

    setNetworkId(id: string) {
        this.networkId = id;
    }

    setIsConnected(connected: boolean) {
        this.isConnected = connected;
    }

    setContractResult(text: string) {
        this.contractResult = text;
    }

    setActiveTab(tab: string) {
        this.activeTab = tab;
    }

    async initializeWeb3() {
        try {
            if ((window as any).ethereum) {
                const web3Instance = new Web3((window as any).ethereum);
                this.setWeb3(web3Instance);
                this.setIsConnected(false);
            } else {
                const httpProvider = new Web3.providers.HttpProvider(
                    'https://mainnet.infura.io/v3/84842078b09946638c03157f83405213'
                );
                const web3Instance = new Web3(httpProvider);
                this.setWeb3(web3Instance);
                this.setIsConnected(true);
                this.setAccount('使用公共节点连接');
                this.setNetworkId('mainnet');
            }
        } catch (error: any) {
            this.setContractResult('初始化Web3失败: ' + error.message);
        }
    }

    async updateBalance(accountAddress: string) {
        if (!this.web3 || !accountAddress) return;
        try {
            const balanceWei = await this.web3.eth.getBalance(accountAddress);
            const balanceEther = this.web3.utils.fromWei(balanceWei, 'ether');
            this.setBalance(balanceEther);
            this.setContractResult(`账户余额更新: ${balanceEther} ETH`);
        } catch (error: any) {
            this.setContractResult('更新余额失败: ' + error.message);
        }
    }
}

const web3DemoStore = new Web3DemoStore();
export default web3DemoStore;

